package com.parlons.activities;

/**
 * Created by wangyifan on 15/12/24.
 */

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.parlons.DatabaseServices;
import com.parlons.R;
import com.parlons.SmackServices;

@SuppressLint("NewApi")
public class FriendsFragment extends Fragment {
    private ListView friendsList;
    public static SimpleCursorAdapter simpleCursorAdapter;
    public static View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.friends, container, false);
        friendsList = (ListView) view.findViewById(R.id.friends_list);
        friendsList.setDividerHeight(0);
        DatabaseServices DBService = DatabaseServices.getInstance(getActivity());
        Cursor cursor = DBService.getFriendsCursor(SmackServices.getUserName());
        simpleCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.friends_item, cursor, new String[]{"friend_username"}, new int[]{R.id.friends_list_username}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        System.out.println("!!!!!!!!!!!!adapter added");
        friendsList.setAdapter(simpleCursorAdapter);// set Adapter for ListView
        DBService.close();
        friendsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                SQLiteCursor cursor = (SQLiteCursor) friendsList.getItemAtPosition(arg2);
                System.out.println("getCount " + cursor.getCount());
                for (String name : cursor.getColumnNames())
                    System.out.println("names: " + name);
                System.out.println("names: " + cursor.getColumnName(1)); // cursor index satrts from 0. here _id, friend_username, friend_name

                Intent i = new Intent(getActivity(), ChatActivity.class);
                i.putExtra("friendName", cursor.getString(1));
                startActivity(i);
                System.out.println(arg2);
            }
        });

        return view;
    }


}
